from flask import Blueprint, jsonify, request
from app.models.database import DorisDatabase
from loguru import logger

db_bp = Blueprint('db', __name__, url_prefix='/api/db')

def init_db_api(db: DorisDatabase):
    @db_bp.route('/query', methods=['POST'])
    def execute_query():

        data = request.get_json()
        query = data.get('query')
        logger.info(f"############## 执行SQL查询：{query} ############")
        if not query:
            return jsonify({"status": "error", "message": "SQL查询不能为空"}), 400
        try:
            results = db.execute_query(query)
            return jsonify({"status": "success", "results": results}), 200
            logger.info(f"############## 查询完成！结果 {results} ############")
        except Exception as e:
            logger.error(f"执行SQL查询失败: {e}")
            return jsonify({"status": "error", "message": str(e)}), 500
    return db_bp